package com.macaline.concurrent;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class ReadWriteTask {

    private volatile Map<String, Object> map = new HashMap<String, Object>();
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();



    public void put(String key, Object value) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始写" + value.toString());
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "完成写" + value.toString());

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void get(String key) {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "开始读" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "完成读" + key);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }
    }


}



public class ReadWriteLockDemo {

    public static void main(String[] args) {
        ReadWriteTask readWriteTask = new ReadWriteTask();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                String num =  finalI + 1 + "";
                readWriteTask.put(num, num);

            }, (i + 1 + "")).start();
        }

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                String num =  finalI + 1 + "";
                readWriteTask.get(num);

            }, (i + 1 + "")).start();
        }
        
    }
}
